﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SQLDB
{
    public class ListToSql
    {
        //保存和更新方法 如果数据存在就更新 如果数据不存在就插入一条新数据
        public int Insert<T>(T obj)
        {
            int count = 0;
            string tableName = obj.GetType().Name.ToString().ToLower();
            string sql = " insert into ";
            sql += tableName + " ( ";
            PropertyInfo[] propertys = obj.GetType().GetProperties();

            foreach (PropertyInfo pro in propertys)
            {
                if (!pro.IsSpecialName)
                    sql += pro.Name + ",";
            }

            sql = sql.Remove(sql.Length - 1);  //删除最后一个 ,和‘
            sql += " ) values( '";
            foreach (PropertyInfo o in propertys)
            {
                if (!o.IsSpecialName)
                    sql += o.GetValue(obj, null) + "' ,'";
            }
            sql = sql.Remove(sql.Length - 2); //删除最后一个 ,和‘
            sql += " ) ";
            count = SQLDB.ExcuteSQL(sql);
            return count;
        }
        //更新数据库
        public int Update<T>(T obj)
        {
            int count = 0;
            string tableName = obj.GetType().Name.ToString().ToLower();
            string sql = " update " + tableName + " set ";

            PropertyInfo[] propertys = obj.GetType().GetProperties();

            foreach (PropertyInfo pro in propertys)
            {
                sql += pro.Name + "='" + pro.GetValue(obj, null) + "',";
            }
            sql = sql.Remove(sql.Length - 1);
            sql += "where id='" + propertys[0].GetValue(obj, null) + "'";
            count = SQLDB.ExcuteSQL(sql);
            return count;
        }
        //删除方法
        public int DelectReal<T>(T obj)
        {
            int count = 0;
            PropertyInfo[] propertys = obj.GetType().GetProperties();
            string tableName = obj.GetType().Name.ToString().ToLower();
            string sql = " delete from  ";
            sql += "where id='" + propertys[0].GetValue(obj, null) + "'";
            count = SQLDB.ExcuteSQL(sql);
            return count;
        }
        //删除方法 逻辑删除
        public int DeleteLogic<T>(T obj)
        {
            int count = 0;
            PropertyInfo[] propertys = obj.GetType().GetProperties();
            string tableName = obj.GetType().Name.ToString().ToLower();
            string sql = " update " + tableName + " set Isdel='0'";
            sql += "where id='" + propertys[0].GetValue(obj, null) + "'";
            count = SQLDB.ExcuteSQL(sql);
            return count;
        }
    }
}
